package com.run_java_test.jar_upload_run.controller.v1;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.util.List;
import java.util.stream.Collectors;

@RequestMapping("get_routes")
@RestController
public class CheckTheRoutesController {

    private final RequestMappingHandlerMapping requestMappingHandlerMapping;

    private final ApplicationContext applicationContext;

    @Autowired
    public CheckTheRoutesController(
            RequestMappingHandlerMapping requestMappingHandlerMapping,
            ApplicationContext applicationContext
    ) {
        this.requestMappingHandlerMapping = requestMappingHandlerMapping;
        this.applicationContext = applicationContext;
    }

    // 查看所有路由
    @GetMapping("routes")
    public List<String> getRoutes() {
        return requestMappingHandlerMapping.getHandlerMethods().keySet().stream()
                .map(RequestMappingInfo::toString)
                .collect(Collectors.toList());
    }

    @GetMapping("getRegisterBean")
    public String getRegisterBean() {
        // 检查 bean 是否存在
        DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) applicationContext.getAutowireCapableBeanFactory();
        // JarController
        if (beanFactory.containsBeanDefinition("jarController")) {
            Object jarController = applicationContext.getBean("jarController");
            System.out.println("查看 jarController Bean : " + jarController);
        } else {
            System.out.println("spring 容器中不存在 jarController Bean");
        }
        // JarService
        if (beanFactory.containsBeanDefinition("jarService")) {
            Object jarController = applicationContext.getBean("jarService");
            System.out.println("查看 jarService Bean : " + jarController);
        } else {
            System.out.println("spring 容器中不存在 jarService Bean");
        }
        return "查看控制台 获取打印 bean 是否存在";
    }

}
